package com.aiss.ws.demo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.aiss.ws.Entity.PayBabyItem;
import com.aiss.ws.R;
import com.aiss.ws.activity.AgreenOnActivity_;
import com.aiss.ws.activity.MycarActivity_;
import com.aiss.ws.activity.SurePayActivity_;
import com.alipay.sdk.app.PayTask;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class PayDemoActivity extends FragmentActivity {

	// 商户PID
	public static final String PARTNER = "2088121894129483";
	// 商户收款账号
	public static final String SELLER = "dfjrwx@163.com";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE =
			"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOAWmlqllfT2LcDP" +
			"AYM9hPDCVG/8Aj4lntD5TRey6E9ioxX9j7SrICsEo0KK0hH6TzP75nqZdVYu5qLx" +
			"u5tgeFFOs9snELxpGcP+WqvBWRckse/DYDTyhox9y0PAlB6wwD5p8sb9MTISfD4j" +
			"mw0JcLiDV/0evpgmzNz8IgD5nTgdAgMBAAECgYB7kZs+Py8o7JOgTcZMw6DKTq7X" +
			"LcVi1cX1AHRVjC90jzTVTIRxIShU8HLCn+BlT31bch3PH05H3wcJdXl5ncHaM//c" +
			"PQ4sni0GGQfm50Fqa/WFf7rOTtTmfRhR0NldC+BnjzOGH+2L2iO3xxvYIuyk4KZe" +
			"WTIDVOktVU0NWv4+VQJBAO+tiOzZfzz7W73aroVRaP5DUmFj1SOdvpLW04Ujvsu5" +
			"kadrsx9rTl+lX9Nh9nf0DOrnV6IWNZ3KOjGSTKGw2Y8CQQDvWUjVvm9Q1/FxV60N" +
			"Y2VgQdlopHUaxmVyUAvVNkKaAYAn/q1wY05q68QebUXBP0xJ2d5dlCgzcvRLKg4Q" +
			"54WTAkBE+i9W4r1gooJjoETrr2NFEcDqsF2N038eKV9UiNYHMY++nBs/5pT2p9Rt" +
			"NFtHaGAzVoL87eFeWO3oiE8vlYL3AkAltUZRTmhRL0Q9nBeKdW9iQ92Rq987MaiH" +
			"4u6KT7scckITiv8eJrcTB0Plm0eTE3rcY7OxwIa43FJ6iQygQyl7AkAJcTiX3zP5" +
			"MZguQryxXLY7h4kxkuQFze9LS56JLgyyclJM+oTVwrK0CWmSBiWnGyMX+92qYQtq" +
			"0wdOTlqvLX8W";
	// 支付宝公钥
	public static final String RSA_PUBLIC =
			"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgFppapZX09i3AzwGDPYTwwlRv" +
			"/AI+JZ7Q+U0XsuhPYqMV/Y+0qyArBKNCitIR+k8z++Z6mXVWLuai8bubYHhRTrPb" +
			"JxC8aRnD/lqrwVkXJLHvw2A08oaMfctDwJQesMA+afLG/TEyEnw+I5sNCXC4g1f9" +
			"Hr6YJszc/CIA+Z04HQIDAQAB";
//商户PID
//public static final String PARTNER = "2088511812679141";
//	//商户收款账号
//	public static final String SELLER = "kf@dbu.cn";
//	//商户私钥，pkcs8格式
//	public static final String RSA_PRIVATE = "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAJrkKAuSChWf/TabbUZ7hwD5NdMC0ImHoamdjjTX3L4gAEMiX49dYn9hB1/X4OS8danNmmb6ofFE4c+RolnWHjnuPn8+gWaZjWWEJTDJAdi+IjT50l0yXF2Dx1pFaycWvUi3fJ1BgxPwdfe5MERcMQmUfXS4wZVSEXS2QYk3wQzhAgMBAAECgYEAgE/vyJ4DkqSF7H3XiaL9VNYeO57CSJw+VTe7PZVxPWNfND4+cZKH7UPhCwnYOUTSKIe1mAearjdE5WIc31UcldEWlOoSlsbf4Q1Jz2eZgyNcFncMD2bXiHxwkhg91BcDRwGB2+GmteRJiR6VtgeCaY5KEnfnzgEECkaIhZj+Hn0CQQDHJNMOeXLihw3r9Uj8E19+1hbPaHUwU+4gUQZ3AkjnWdPg44Fw5n/zzm3MNrRI+6c3Cj21JxyvtbApOVyLIcy7AkEAxxz2weqSTa+YNmuNFvtCFBgrfGC3/Mtl+N4ANYZcWWezOlK/1wf3l/TgsSDxPPOGYJ7aCYxTXqtw+62Y3ERhEwJBAIzkmcow1L4+LPRXCvcFQdf74hGF5vt1NhF5IejLHgdIf2Ypr+fPvJEi6H3F6lGEci63uSbUcDBEjEjuQ3JQTIcCQQCUTLJNBBUr31kTT0+qikFRDh91Z+QhWKz+ivrE4untfRs0mWVhFwIGH9EqnEqRByBS3n2vFuERZcek7Esp45QZAkEAu1BrWWaiY2JlqzVjzR+hy75dpwyiqN6wOzNIOfPrC0qony5IzQNtz6GLVqe+/UV3ofGYWVohfr0klW5lFlH93Q==";
//	//支付宝公钥
//	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAUK2/BZ4Tr6c4kB55XHPAWSeFBKrCl/ONkdU1kpmFHXIEIHTexlHwArqVwUYZRaqBvk09t1PoCPPivKepiNaUthfuNOTww/hv9gCT3cR9iEmjvKIkEIzlwcfGVfD+19n/A8wN3pJddv3MyGAnjSm67L994lppaP9L+rhgLadUEwIDAQAB";


	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_CHECK_FLAG = 2;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					if(SurePayActivity_.getActivity()!=null&& !SurePayActivity_.getActivity().isFinishing()){
						SurePayActivity_.getActivity().finish();
					}
					if(AgreenOnActivity_.getActivity()!=null&& !AgreenOnActivity_.getActivity().isFinishing()){
						AgreenOnActivity_.getActivity().finish();
					}

					if(MycarActivity_.getActivity()!=null&&!MycarActivity_.getActivity().isFinishing()){
						MycarActivity_.getActivity().finish();
					}


					finish();
					Toast.makeText(PayDemoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayDemoActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayDemoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(PayDemoActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	private PayBabyItem item;

	private TextView product_subject;
	private TextView body;
	private TextView product_price;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay_main);
		Intent intent = getIntent();
		item = (PayBabyItem) intent.getSerializableExtra("item");
		product_price = (TextView) findViewById(R.id.product_price);
		body = (TextView) findViewById(R.id.body);
		product_subject = (TextView) findViewById(R.id.product_subject);
		product_price.setText(item.getTotal_fee()+"元");
		body.setText(item.getBody());
		product_subject.setText(item.getSubject());

	}

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(View v) {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {
							//
							finish();
						}
					}).show();
			return;
		}
		String orderInfo = getOrderInfo(item.getSubject(), item.getBody(), item.getTotal_fee());

		/**
		 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(PayDemoActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(PayDemoActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
	 * 
	 * @param v
	 */
	public void h5Pay(View v) {
		Intent intent = new Intent(this, H5PayDemoActivity.class);
		Bundle extras = new Bundle();
		/**
		 * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
		 * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
		 * 商户可以根据自己的需求来实现
		 */
		String url = "http://m.taobao.com";
		// url可以是一号店或者美团等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
		extras.putString("url", url);
		intent.putExtras(extras);
		startActivity(intent);

	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + item.getOut_trade_no() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + item.getSubject() + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + item.getBody() + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + item.getTotal_fee() + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + item.getNotify_url() + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
